<template>
  <div class="register-container">
    <div>
      <div class="register-header">
        <van-icon name="arrow-left" class="back-icon" @click="router.back()" />
      </div>
      <div class="register-form-wrapper">
        <div class="logo-section">
          <img src="../assets/icons/register.svg" alt="" />
        </div>

        <form @submit.prevent="handleRegister" class="register-form">
          <!-- 用户名 -->
          <div class="form-group">
            <input
              type="text"
              id="username"
              v-model="form.username"
              placeholder="用户名"
              maxlength="8"
            />
          </div>

          <!-- 账号 -->
          <div class="form-group">
            <input
              type="text"
              id="account"
              v-model="form.account"
              placeholder="账号"
            />
          </div>

          <!-- 密码 -->
          <div class="form-group">
            <input
              type="text"
              id="password"
              v-model="form.password"
              placeholder="密码"
            />
          </div>

          <!-- 邮箱 -->
          <div class="form-group">
            <input
              type="text"
              id="email"
              v-model="form.email"
              placeholder="邮箱"
            />
          </div>

          <!-- 邮箱验证码 -->
          <div class="form-group">
            <div class="verification-code-container">
              <input
                type="text"
                id="verificationCode"
                v-model="form.verificationCode"
                placeholder="输入验证码"
                maxlength="6"
              />
              <button
                type="button"
                class="send-code-button"
                @click="handleSendVerificationCode"
                :disabled="countdown > 0"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : "获取验证码" }}
              </button>
            </div>
          </div>

          <button type="submit" class="register-button">
            {{ loading ? "注册中..." : "注册" }}
          </button>
        </form>
      </div>
    </div>
    <!-- 加载状态 -->
    <div class="loading-state" v-if="sendCodeLoading">
      <van-loading type="spinner" color="#6c63ff" size="48px" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "../store/user";
import axios from "../utils/axios";
import { showToast } from "vant";

const router = useRouter();
const userStore = useUserStore();

// 表单数据
const form = ref({
  username: "",
  account: "",
  email: "",
  password: "",
  verificationCode: "",
});

// 验证码相关
const tempUserId = ref("");
const countdown = ref(0);
let countdownTimer = null;

// 表单状态
const loading = ref(false);

// 发送验证码loading状态
const sendCodeLoading = ref(false);

// 清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});

// 发送验证码
async function handleSendVerificationCode() {
  // 账号验证
  const account = form.value.account.trim();
  if (!account) {
    showToast({ message: "账号不能为空", position: "bottom" });
    return;
  }
  const accountRegex = /^[0-9]{8,12}$/;
  if (!accountRegex.test(account)) {
    showToast({
      message: "账号只能包含数字，长度8-12位",
      position: "bottom",
    });
    return;
  }
  // 邮箱验证
  const email = form.value.email.trim();
  if (!email) {
    showToast({ message: "邮箱不能为空", position: "bottom" });
    return;
  }

  // 3646647918

  // 检查是否在倒计时中
  if (countdown.value > 0) {
    showToast({ message: `${countdown.value}秒后重试`, position: "bottom" });
    return;
  }

  try {
    sendCodeLoading.value = true;
    const response = await axios.post("/users/send-verification-code", {
      email: form.value.email,
      account: form.value.account,
      name: form.value.username,
    });
    sendCodeLoading.value = false;

    tempUserId.value = response.tempUserId;

    // 开始倒计时
    startCountdown();
  } catch (err) {
    sendCodeLoading.value = false;
    showToast({
      message: err.response?.message || "发送验证码失败，请稍后再试",
      position: "bottom",
    });
  }
}

// 开始倒计时
function startCountdown() {
  countdown.value = 60;

  if (countdownTimer) {
    clearInterval(countdownTimer);
  }

  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer);
    }
  }, 1000);
}

// 处理注册
async function handleRegister() {
  // 处理注册

  // 实现完整的表单校验
  if (!form.value.username.trim()) {
    showToast({ message: "用户名不能为空", position: "bottom" });
    return;
  }
  if (form.value.username.length > 8) {
    showToast({ message: "用户名不能超过8个字符", position: "bottom" });
    return;
  }

  if (!form.value.account.trim()) {
    showToast({ message: "账号不能为空", position: "bottom" });
    return;
  }
  const accountRegex = /^[0-9]{8,12}$/;
  if (!accountRegex.test(form.value.account)) {
    showToast({
      message: "账号只能包含数字，长度8-12位",
      position: "bottom",
    });
    return;
  }
  if (!form.value.password) {
    showToast({ message: "请输入密码", position: "bottom" });
    return;
  }
  const passwordRegex = /^[a-zA-Z0-9\W_]{8,18}$/;
  if (!passwordRegex.test(form.value.password)) {
    showToast({
      message: "密码只能包含字母、数字和特殊字符，长度8-18个字符",
      position: "bottom",
    });
    return;
  }

  if (!form.value.email.trim()) {
    showToast({ message: "邮箱不能为空", position: "bottom" });
    return;
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(form.value.email)) {
    showToast({ message: "邮箱格式不正确", position: "bottom" });
    return;
  }

  if (!form.value.verificationCode.trim()) {
    showToast({ message: "请输入验证码", position: "bottom" });
    return;
  }
  if (!/^\d{6}$/.test(form.value.verificationCode)) {
    showToast({ message: "验证码格式不正确", position: "bottom" });
    return;
  }

  loading.value = true;

  try {
    const response = await axios.post("/users/register", {
      name: form.value.username,
      account: form.value.account,
      email: form.value.email,
      password: form.value.password,
      verificationCode: form.value.verificationCode,
      tempUserId: tempUserId.value,
    });

    showToast({
      message: "注册成功",
      position: "bottom",
    });

    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      router.push("/login");
    }, 2000);
  } catch (err) {
    // 如果有具体的密码要求错误，显示更详细的信息
    if (err.response?.data?.requirements) {
      showToast({
        message: `密码需要满足：${err.response.data.requirements.join("、")}`,
        position: "bottom",
      });
    } else {
      showToast({
        message: err.response?.data?.message || "注册失败，请稍后再试",
        position: "bottom",
      });
    }
  } finally {
    loading.value = false;
  }
}

// 重复的脚本部分已删除
</script>

<style scoped>
.register-container {
  height: 100vh;
  background: white;
}
.register-header {
  display: flex;
  align-items: center;
  padding: 20px 20px 0;
  background: white;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.back-icon {
  font-size: 20px;
  color: #1d2129;
  margin-right: 5px;
}

.register-form-wrapper {
  padding: 30px 40px 40px;
  width: 100%;
  box-sizing: border-box;
  background: white;
}

.logo-section {
  text-align: center;
  margin: 0 auto;
  margin-bottom: 30px;
  width: 80%;
}

.register-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: none;
  border-bottom: 1px solid #d9dde1;
  font-size: 14px;
  /* transition: border-color 0.3s; */
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  /* border-color: #1677ff; */
  /* box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.1); */
}

.form-group input:disabled {
  cursor: not-allowed;
}

/* 验证码输入框容器 */
.verification-code-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.verification-code-container input {
  flex: 1;
  /* width: 70%; */
}

.send-code-button {
  padding: 10px 5px;
  background-color: #000000;
  color: #ffffff;
  border: none;
  border-radius: 18px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
  width: 30%;
}
.send-code-button:disabled {
  background-color: #d9dde1;
  cursor: not-allowed;
}

.register-button {
  background-color: #000000;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 18px 24px;
  font-size: 20px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 10px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #4e5969;
}

.login-link a {
  color: #1677ff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 加载状态 */
.loading-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
}
</style>
